package com.yy.permissions_general.module.system.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yy.permissions_general.common.constant.SystemConstant;
import com.yy.permissions_general.common.config.exception.base.ServiceException;
import com.yy.permissions_general.module.system.user.entity.User;
import com.yy.permissions_general.module.system.user.mapper.UserMapper;
import com.yy.permissions_general.module.system.user.service.UserRoleService;
import com.yy.permissions_general.module.system.user.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.permissions_general.utils.FTP;
import com.yy.permissions_general.utils.encrypt.AESUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author YY
 * @since 2021-10-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserRoleService userRoleService;

    /**
    * 分页查询列表
    * @param user
    * @return
    */
    @Override
    public  Page<User>selectPageList(User user, int limit, int page)  {
        Page pageContext = new Page(page,limit);
        Page<User> pageList = this.baseMapper.selectPage(pageContext, user);
        return pageList;
    }

    /**
    * 新增数据
    * @param user
    */
    @Override
    public int addUser(User user, MultipartFile file) {
        if (file != null && !file.isEmpty()){
            String fileName = file.getOriginalFilename();
            UUID uuid = UUID.randomUUID();
            String newName = uuid.toString()+fileName.substring(fileName.lastIndexOf("."));
            user.setHeadImg(SystemConstant.USER_MODULE_FILE +"/"+newName);
            try {
                FTP.upload(newName, file.getInputStream(), SystemConstant.USER_MODULE_FILE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            user.setPassword(AESUtil.aesEncrypt(SystemConstant.PASS_WORD,AESUtil.KEY_STR));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setStatus(0);
        int userId = baseMapper.insert(user);
        userRoleService.insertUserRole(user.getId(),user.getRoleIds());
        return userId;
    }

    /**
    * 修改数据
    * @param user
    */
    @Override
    public int editUser(User user, MultipartFile file) {
        if (file != null && !file.isEmpty()){
            /*删除原来头像*/
            User checkUser = this.baseMapper.selectById(user.getId());
            if (checkUser == null)throw new ServiceException(400,"未查询到用户~");
            if (StringUtils.isNotEmpty(checkUser.getHeadImg())){
                FTP.deleteFile("",checkUser.getHeadImg());
            }
            String fileName = file.getOriginalFilename();
            UUID uuid = UUID.randomUUID();
            String newName = uuid.toString()+fileName.substring(fileName.lastIndexOf("."));
            user.setHeadImg(SystemConstant.USER_MODULE_FILE +"/"+newName);
            try {
                FTP.upload(newName, file.getInputStream(), SystemConstant.USER_MODULE_FILE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(user.getRoleIds())){
            userRoleService.deleteByUserId(user.getId());
            userRoleService.insertUserRole(user.getId(),user.getRoleIds());
        }
        return baseMapper.updateById(user);
    }

    /**
    * 查看详情
    * @param id
    * @return
    */
    @Override
    public User getDetailsById(Integer id) {
        return baseMapper.selectById(id);
    }

    /**
    * 删除数据
    * @param id
    * @return
    */
    @Override
    public int deleteById(Integer id) {
        /*删除原来头像*/
        User checkUser = this.baseMapper.selectById(id);
        if (checkUser == null)throw new ServiceException(400,"未查询到用户~");
        if (StringUtils.isNotEmpty(checkUser.getHeadImg())) {
            FTP.deleteFile("", checkUser.getHeadImg());
        }
        userRoleService.deleteByUserId(id);
        return baseMapper.deleteById(id);
    }

    /**
    * 批量删除
    * @param ids
    * @return
    */
    @Override
    public int deleteBatch(List<Long> ids) {
        /*删除原来头像*/
        List<User> userList = this.baseMapper.selectBatchIds(ids);
        if (CollectionUtil.isEmpty(userList))throw new ServiceException(400,"未查询到用户~");
        userList.forEach(user ->{
            if (StringUtils.isNotEmpty(user.getHeadImg())){
                    FTP.deleteFile("",user.getHeadImg());
            }
            userRoleService.deleteByUserId(user.getId());
        });
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int updateUser(User user) {
        return baseMapper.updateById(user);
    }

    @Override
    public int updatePassword(Map<String, Object> map) {
        //判断原始密码是否输入正确
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        int resultInt = 0;
        try {
            queryWrapper.eq("account",map.get("account"));
            queryWrapper.eq("password",AESUtil.aesEncrypt(Convert.toStr(map.get("oldPassword")),AESUtil.KEY_STR));
            User user = this.getOne(queryWrapper);
            if (user == null)throw new ServiceException(400,"原始密码不正确~");
            User newUser = new User();
            newUser.setId(user.getId());
            newUser.setPassword(AESUtil.aesEncrypt(Convert.toStr(map.get("password")),AESUtil.KEY_STR));
            resultInt = this.baseMapper.updateById(newUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultInt;
    }



}

